package com.RabbitMQ.simple.Customer;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Created by thinkjoy on 2017/6/29.
 */
public class Customer {
    public final static String QUEUE_NAME="rabbitMQ_queue_thinkjoy";

    public static void main(String[] args) throws IOException,TimeoutException {
        ConnectionFactory factory=new ConnectionFactory();//创建连接工厂
//        设置RabbitMQ相关消息
        factory.setHost("localhost");
//        创建一个新连接
        Connection connection=factory.newConnection();
//        创建一个通道
        Channel channel=connection.createChannel();
        /**
         * 声明一个队列
         * 参数:队列名称,是否持久化,是否独占队列,当所有消费者客户端连接断开时是否自动删除队列,队列的其他参数
         */
        channel.queueDeclare(QUEUE_NAME,false,false,false,null);
        System.out.println("消费者正在等待接收消息");
        Consumer consumer=new DefaultConsumer(channel){
            @Override
            /**
             * envelope:存放的是生产者相关消息
             */
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
               String message=new String(body,"UTF-8");
                System.out.println("消费者收到的消息是:"+message);
            }
        };
//        自动回复队列应答(消息确认机制)
        channel.basicConsume(QUEUE_NAME,true,consumer);
    }
}
